<?php
/**
 * Created by PhpStorm.
 * User: jacob
 * Date: 18-10-17
 * Time: 下午2:55
 */
namespace Api\Common;

use Common\HttpStatus;
use Common\Logger;
use Common\PlutoApi;
use Common\Request;
use Common\RequestApi;
use Common\Response;
use Common\ResponseApi;
use DB\Home\AccountUser;
use DB\VerifyCode;

class SendEmailRequest extends RequestApi{
  /**
   * @var string 邮箱地址
   */
  public $email;
}

class SendEmailResponse extends ResponseApi{
  /**
   * @var string 提示信息
   */
  public $message;
}

class SendEmail extends PlutoApi{
  protected function run(Request $request, Response $response) {
    /**
     * @var $rqData SendEmailRequest
     */
    $rqData = $request->data;
    if (empty($rqData->email) || !is_string($rqData->email)){
      $response->httpStatus = HttpStatus::PARAMETER_ERROR;
      $response->httpMessage = "email is not set or is not string";
      return;
    }
    $user = new AccountUser();
    if(!$user->verifyEmail($rqData->email)){
      $response->httpStatus = HttpStatus::Forbidden;
      $response->httpMessage = "email is alreay exists";
      return;
    }
    $verifyCode = new VerifyCode();
    $verifyCode->initVerifyCode($rqData->email);
    $content = "你好，你的验证码为：".$verifyCode->getVerifyCode();
    $sendMail = new \Common\SendEmail();
    //使用子进程发送邮件
    $pid = pcntl_fork();
    if ($pid == -1){
      $response->httpStatus = HttpStatus::ERROR;
      $response->httpMessage = "fork is error";
      return;
    }elseif ($pid == 0){
      //子进程
      $res = $sendMail->sendEmail($rqData->email,$content);
      if (!$res){
        Logger::getInstance()->info("$rqData->email is send email failed");
      }
    }else{
      //主进程
      $response->data = new SendEmailResponse();
      $response->data->message = "发送成功";
    }
  }
}